//
//  FeedbackVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/3/22.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit

class ZyaFeedbackFormVC: GlobalFormVC,operatable,DateWidgetable,refreshable,KSImageUtilDelegate {
    
    
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
            .roundType(.top)
        
        let v = KSFormHItem(title: "出价标题*",appearance:appe)
        return v
    }()
    var item2 :KSFormHItem = {
        let appe = KSFormHAppear()
            .placeholder("请输入您的反馈意见")
            .contentHight(150)
        let v = KSFormHItem(title: "意见*",appearance:appe,type: .tempTextView )
        return v
    }()
    lazy var saveButton: KSUIButton = {
        let button = KSUIButton(titlex: "提交")
        
        return button
    }()
    var one = FeedBaceModel(JSON:["":""])!
     var imageArray = [VideoImg]()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "意见反馈"
        
        if self.excuteType  == .view {
            let rightBtn = UIButton.creat4Item(image: UIImage(named:"del")!) { _ in
                alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
                    KSNetwork.shared.doRequest(API.delFeedbackInfo(id_key: self.one.id_key.unwrap)) { (data:BaseResult<FeedBaceModel>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            if let clo = self.refreshClosure {
                                clo()
                            }
                            self.navigationController?.popViewController(animated: true)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                })])
            }
            let right = UIBarButtonItem(customView: rightBtn)
            self.navigationItem.rightBarButtonItem = right
            KSNetwork.shared.doRequest(API.getFeedbackInfo(id_key: one.id_key.unwrap)) { (data:BaseResult<FeedBaceModel>) in
                if data.flag == TRUE {
                    if let info = data.infoObjCombine {
                        self.one = info
                        if let list = info.pic_list {
                            self.imageArray = list.compactMap({ one in
                                var ttt:SourType = .image
                                if one.z_url.unwrap.contains("mp4") {
                                    ttt = .video
                                } else if one.z_url.unwrap.contains("pdf") {
                                    ttt = .file
                                }
                                let newone = VideoImg(type: ttt, idkey: one.id_key,url: one.z_url, name: "文件")
                       
                                return newone
                            })
                        }
                        self.configRow()
                    }
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            let rightBtn = UIButton.creat4Item(image: UIImage(named:"shijian_x")!) { _ in
                let vc = ZyaFeedBackListVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            let right = UIBarButtonItem(customView: rightBtn)
            self.navigationItem.rightBarButtonItem = right
            self.configRow()
        }
        
         
        
        
        
    }
    func configRow() {
        self.configView()
        self.configAction()
        self.configDataSource()
        
    }
    
    
    func addImages(_ util: KSImageSelectUtil, imgs: [UIImage]) {
        //有了另一个这个就不用了，但是协议了又是必须的，为了兼容， 待Fix
    }
    func addImages(_ util: KSImageSelectUtil, imgvideos: [VideoImg]) {
             self.imageArray += imgvideos
        
    }
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        
        self.imageArray.remove(at: index)
        self.imageUtil!.deleteLocalImg(tag: index)
        
    }
    func addFiles(_ util: KSImageSelectUtil, files: [VideoImg]) {
        self.imageArray += files
     }
    
    func configView() {
        if self.excuteType == .view {
            self.bg.disableForm()
        }
        bg.add(item1)
            .add(item2)
        
        let viewFlag:ImgViewType = excuteType == .add ? .editable : .viewOnly
        imageUtil = KSImageSelectUtil(frame: CGRect(x:0,y:item2.frame.maxY,width:bg.ks_width ,height:imgHeight),httpHeader: "",maxImgCount: 9,numberOfRow: 5,picType: [.takePicture,.albumPicture,.albumVideo,.allfile],viewType: viewFlag)
        imageUtil?.ksDelegate = self
        bg.addv(view:imageUtil!)
        imageUtil?.u_superVC = self
        
        let urls = self.imageArray.filter{$0.type == .image}.compactMap { configURLOK(latter:$0.url.unwrap)   }
        self.imageUtil!.showPicture(urls: urls, backImgs: { (imgA) in
            if imgA.isSome {
                for i in 0..<imgA!.count {
                    self.imageArray[i].image = imgA![i]
                }
            }
            
        })
        self.imageUtil!.showAllFiles(files: self.imageArray.filter{$0.type == .file || $0.type == .video})
        
        if self.excuteType == .add {
            bg.add(saveButton)
        }
        
        header.ks_height = bg.frame.maxY + 10
    }
    func configAction() {
        saveButton.button.addTouchUpInSideAction { _ in
            self.saveAction()
        }
        
        item1.actionClosure = {
            let vc = ZyaTenderJpChooseVC(listType:.JP,titleStr:.jpListKHW)
            vc.backClosure = { backone in
                
                self.one.z_zb_id = backone.zZbId
                self.one.z_zb_no = backone.zRecordNo
                self.one.z_zb_title = backone.zTitle
                self.configDataSource()
            }
            self.navigationController?.pushViewController(vc, animated: true)
            
            
        }
        item2.textValueChangeClo = { str in
            self.one.z_content = str
        }
        
    }
    func configDataSource() {
        item1.setVal(one.z_zb_title)
        item2.setVal(one.z_content)
        
    }
    
    func saveAction() {
        guard self.judgeNoNone() else {
            return
        }
        
         let vArr = self.imageArray.filter{ $0.type == .video }
        if vArr.count > 0 {
            // 创建调度组
            let workingGroup = DispatchGroup()
            
            for i in 0..<self.imageArray.count {
                if self.imageArray[i].type == .video {
                    // 入组
                    workingGroup.enter()
                    assetToData(asset: self.imageArray[i].asset!, result: { data in
                        self.imageArray[i].data = data
                        // 出组
                        workingGroup.leave()
                    })
                    
                }
            }
            // 调度组里的任务都执行完毕
            workingGroup.notify(queue: .main) {
                 self.saveContinue()
            }
        
                    
        } else {
            self.saveContinue()
        }
        
        
        
    }
    func saveContinue() {
        let dic = ["id_key":"","z_zb_title":"\(self.one.z_zb_title.unwrap)","z_zb_id":"\(self.one.z_zb_id.unwrap)","z_content":"\(self.one.z_content.unwrap)","z_zb_no":"\(self.one.z_zb_no.unwrap)"]
        KSNetwork.shared.doRequest(API.saveFeedbackInfo(data: dictionaryToJson(dic), files: self.imageArray)) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                KSToast("提交成功")
                self.navigationController?.popViewController(animated: true)
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
}
